package com.hlj.ncp.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.header.writers.StaticHeadersWriter;

import com.hlj.ncp.service.UserAuthService;

/**
 * Spring Security 配置
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserAuthService userAuthService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 配置 Spring Security
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                // 允许访问静态资源
                .antMatchers("/css/**", "/js/**", "/images/**", "/fonts/**", "/static/**").permitAll()
                // 允许访问登录页面和登录处理
                .antMatchers("/login", "/login?error").permitAll()
                // 允许访问Swagger文档
                .antMatchers("/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**").permitAll()
                // 其他所有请求需要认证
                .anyRequest().authenticated()
                .and()
            .formLogin()
                // 自定义登录页
                .loginPage("/login")
                // 登录处理URL
                .loginProcessingUrl("/login")
                // 登录成功后跳转
                .defaultSuccessUrl("/index")
                .permitAll()
                .and()
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login?logout")
                .permitAll()
                .and()
            // CSRF保护
            .csrf()
                // 对订单相关接口禁用CSRF保护
                .ignoringAntMatchers("/finance/order/**", "/system/user/**", "/stock/**", "/product/**")
                .and()
            // 禁用X-Frame-Options，允许iframe加载
            .headers()
                .frameOptions().disable()
                .and()
            .exceptionHandling()
                .accessDeniedPage("/error/403");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userAuthService).passwordEncoder(passwordEncoder);
    }
} 